<template>
  <div>
    <h1>课程管理系统</h1><br>
    <el-table
        ref="resourceTableRef"
        :data="courseList"
        border
        row-key="id"
        style="width: 100%"
    >
      <el-table-column prop="id" label="编号" align="center" width="80" />
      <el-table-column prop="courseName" label="课程名" min-width="120" />
      <el-table-column prop="courseDesc" label="课程简介" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column prop="openDuration" label="开放时间（天）" align="center" width="120" />
      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="stop" label="是否结束" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.stop ? 'danger' : 'success'">
            {{ scope.row.stop ? '已结束' : '进行中' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="140" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="修改课程信息"
        width="1200px"
    >
      <el-form
          :model="editForm"
          label-width="120px"
          ref="editFormRef"
      >
        <el-form-item label="课程名">
          <el-input v-model="editForm.courseName" />
        </el-form-item>
        <el-form-item label="课程简介">
          <el-input
              v-model="editForm.courseDesc"
              type="textarea"
              :rows="3"
          />
        </el-form-item>
        <el-form-item label="开放时间（天）">
          <el-input-number v-model="editForm.openDuration" :min="1" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="editForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="editForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
          />
        </el-form-item>
        <el-form-item label="是否结束">
          <el-switch v-model="editForm.stop" />
        </el-form-item>
      </el-form>

      <div class="resource-section">
        <!-- 已添加资源表 -->
        <h3>已添加资源</h3>
        <el-table
            :data="addedResources"
            border
            style="width: 100%; margin-bottom: 20px;"
            highlight-current-row
            row-key="id"
        >
          <el-table-column prop="id" label="编号" width="80" align="center" />
          <el-table-column prop="resourceName" label="资源名" width="180" show-overflow-tooltip />
          <el-table-column prop="isDocument" label="类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isDocument ? 'warning' : 'success'">
                {{ scope.row.isDocument ? '视频' : '文档' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="resourceTotalDuration" label="时长" width="100" align="center">
            <template #default="scope">
              {{ formatDuration(scope.row.resourceTotalDuration) }}
            </template>
          </el-table-column>
          <el-table-column prop="resourceUrl" label="地址" show-overflow-tooltip />
          <el-table-column prop="tagId" label="标签" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="getTagName(scope.row.tagId)" type="info">
                {{ getTagName(scope.row.tagId) }}
              </el-tag>
              <span v-else class="no-tag">无标签</span>
            </template>
          </el-table-column>
          <el-table-column prop="resourceDesc" label="说明" show-overflow-tooltip />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button size="small" type="danger" @click="handleRemoveResource(scope.row.id)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <h3>所有资源</h3>
        <el-table
            :data="paginatedResources"
            border
            style="width: 100%"
            highlight-current-row
            row-key="id"
        >
          <el-table-column prop="id" label="编号" width="80" align="center" />
          <el-table-column prop="resourceName" label="资源名" width="180" show-overflow-tooltip />
          <el-table-column prop="isDocument" label="类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isDocument ? 'warning' : 'success'">
                {{ scope.row.isDocument ? '视频' : '文档' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="resourceTotalDuration" label="时长" width="100" align="center">
            <template #default="scope">
              {{ formatDuration(scope.row.resourceTotalDuration) }}
            </template>
          </el-table-column>
          <el-table-column prop="resourceUrl" label="地址" show-overflow-tooltip />
          <el-table-column prop="tagId" label="标签" width="120" align="center">
            <template #default="scope">
              <el-tag v-if="getTagName(scope.row.tagId)" type="info">
                {{ getTagName(scope.row.tagId) }}
              </el-tag>
              <span v-else class="no-tag">无标签</span>
            </template>
          </el-table-column>
          <el-table-column prop="resourceDesc" label="说明" show-overflow-tooltip />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                  size="small"
                  type="primary"
                  @click="handleAddResource(scope.row)"
                  :disabled="isResourceAdded(scope.row.id)"
              >
                {{ isResourceAdded(scope.row.id) ? '已添加' : '添加' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="allResources.length > 0">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="allResources.length"
              :page-size="pagination.pageSize"
              :current-page="pagination.pageNum"
              :page-sizes="[5, 10, 20, 50]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { Course } from '@/types/course.ts'
import type { TrainingResource, CourseResource } from '@/types/resourse.ts'
import { reactive, ref, onMounted, computed, watch } from 'vue'
import { ElMessage, type ElTable, type FormInstance } from 'element-plus'
import request from "@/utils/request.ts"

const courseList = ref<Course[]>([])
const dialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const courseResources = ref<CourseResource[]>([])
// 定义标签类型
interface Tag {
  id: number
  tagName: string
  // 可以根据实际接口返回的字段添加其他属性
}
const allTag = ref<Tag[]>([])
interface Resource {
  id: number
  resourceName: string
  isDocument: boolean
  resourceTotalDuration: number
  resourceUrl: string
  tagId: number
  resourceDesc: string
}

const allResources = ref<Resource[]>([])

// 修改 editForm，添加 resourceIds 属性
const editForm = reactive<Partial<Course> & { resourceIds?: number[] }>({
  id: 0,
  courseName: '',
  courseDesc: '',
  openDuration: 0,
  startTime: '',
  endTime: '',
  stop: false,
  resourceIds: [] // 添加 resourceIds 属性
})

// 分页配置
const pagination = reactive({
  pageNum: 1,
  pageSize: 5
})

// 计算已添加的资源（根据courseResources中的resourceId匹配allResources）
const addedResources = computed(() => {
  return courseResources.value.map(cr => {
    const resource = allResources.value.find(r => r.id === cr.resourceId)
    return resource ? { ...resource } : null
  }).filter(Boolean) as Resource[]
})

// 计算分页后的资源数据（排除已添加的资源）
const paginatedResources = computed(() => {
  const start = (pagination.pageNum - 1) * pagination.pageSize
  const end = start + pagination.pageSize

  // 过滤掉已添加的资源
  const availableResources = allResources.value.filter(resource =>
      !courseResources.value.some(cr => cr.resourceId === resource.id)
  )

  return availableResources.slice(start, end)
})

// 检查资源是否已添加
const isResourceAdded = (resourceId: number) => {
  return courseResources.value.some(cr => cr.resourceId === resourceId)
}

// 同步 resourceIds 到 editForm
const syncResourceIds = () => {
  editForm.resourceIds = courseResources.value.map(cr => cr.resourceId)
  console.log('同步后的 resourceIds:', editForm.resourceIds)
}

// 监听 courseResources 变化，自动同步到 editForm.resourceIds
watch(courseResources, () => {
  syncResourceIds()
}, { deep: true })

onMounted(() => {
  getAllCourses()
  selectAllResource()
  selectAllTag()
})

const getAllCourses = () => {
  request.get('/course/list').then(res => {
    courseList.value = res.data.list
  })
}

const selectAllTag = async () => {
  try {
    const res = await request.get("/trainingTag/list")
    if (res.data && res.data.trainingTags) {
      allTag.value = res.data.trainingTags
      console.log('获取到的所有标签数据:', allTag.value)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 处理编辑按钮点击
const handleEdit = (row: Course) => {
  Object.assign(editForm, row)
  dialogVisible.value = true
  console.log(row)
  request.get('courseResource/selectResource?courseId=' + row.id).then(res => {
    courseResources.value = res.data.resources || []
    console.log('已添加的资源:', courseResources.value)
    // 初始化时同步 resourceIds
    syncResourceIds()
  })
}

//处理删除
const handleDelete = (row: Course) => {
  request.get('/course/delete?id=' + row.id).then(res => {
    getAllCourses();
  })
}

// 添加资源 - 直接操作 resourceIds
const handleAddResource = (resource: Resource) => {
  if (isResourceAdded(resource.id)) {
    ElMessage.warning('该资源已添加')
    return
  }

  // 直接添加到 courseResources
  courseResources.value.push({
    courseId: editForm.id!,
    resourceId: resource.id
  })

  ElMessage.success('添加资源成功')
  console.log('添加资源后的 resourceIds:', editForm.resourceIds)
}

// 移除资源 - 直接操作 resourceIds
const handleRemoveResource = (resourceId: number) => {
  // 从 courseResources 中移除
  const index = courseResources.value.findIndex(cr => cr.resourceId === resourceId)
  if (index > -1) {
    courseResources.value.splice(index, 1)
    ElMessage.success('移除资源成功')
    console.log('移除资源后的 resourceIds:', editForm.resourceIds)
  }
}

// 获取所有资源列表
const selectAllResource = async () => {
  const res = await request.get("/trainingResource/allList")
  allResources.value = res.data.resourceList
  console.log(allResources.value)
}

// 处理保存
const handleSave = () => {
  // 确保 resourceIds 是最新的
  syncResourceIds()

  console.log('保存时的数据:', {
    ...editForm,
    resourceIds: editForm.resourceIds
  })

  request.post('/course/update', editForm).then(res => {
    ElMessage.success('修改成功')
    dialogVisible.value = false
    getAllCourses()
  }).catch(error => {
    ElMessage.error('修改失败')
  })
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNum = 1 // 重置到第一页
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageNum = page
}

// 格式化时长
const formatDuration = (seconds: number) => {
  if (!seconds) return '0秒'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}时${minutes}分${secs}秒`
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`
  } else {
    return `${secs}秒`
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

// 获取标签名称（需要根据实际情况实现）
const getTagName = (tagId: number) => {
  if (!tagId) return null

  const tag = allTag.value.find(tag => tag.id === tagId)
  return tag ? tag.tagName : null
}
</script>

<style scoped>
.resource-section {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.resource-section h3 {
  margin-bottom: 15px;
  color: #409EFF;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.no-tag {
  color: #999;
  font-size: 12px;
}

.added-resources-table {
  margin-bottom: 20px;
}
</style>